<?php

namespace App\Entity;

use App\Enum\LogTypeEnum;
use App\Utils\Helper\GeneralHelper;
use App\Utils\Helper\LogHelper;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\AdminUserRepository")
 * @ORM\HasLifecycleCallbacks()
 * @UniqueEntity("username")
 * @UniqueEntity("email")
 */
class AdminUser implements UserInterface {

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true, options={"comment"="Email"})
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255, unique=true, options={"comment"="用户名"})
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255, nullable=true, options={"comment"="昵称"})
     */
    private $nickname;

    /**
     * @ORM\Column(type="json")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     * @Assert\Regex(
     *     pattern="/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]+$/",
     *     message="密码应包含数字和字母"
     * )
     * @Assert\Length(
     *      min = 6,
     *      max = 20,
     *      minMessage = "密码最少 {{ limit }} 个字符",
     *      maxMessage = "密码最多 {{ limit }} 个字符"
     * )
     */
    private $password;

    /**
     * @ORM\Column(type="integer", nullable=true, options={"default"="0","comment"="模块组ID"})
     */
    private $admin_user_group_id = 0;

    /**
     * @var \DateTime|null
     *
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $created_at;

    /**
     * @var \DateTime|null
     *
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $updated_at;

    /**
     * @ORM\Column(type="string", length=255, nullable=true, options={"comment"="头像"})
     */
    private $avatar;

    public $avatar_item;

    public function getId (): ?int {
        return $this->id;
    }

    public function getEmail (): ?string {
        return $this->email;
    }

    public function setEmail (string $email): self {
        $this->email = $email;

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername (): string {
        return (string)$this->username;
    }

    /**
     * @see UserInterface
     */
    public function getRoles (): array {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles (array $roles): self {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword (): string {
        return (string)$this->password;
    }

    public function setPassword ($password): self {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt () {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials () {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    public function getCreatedAt (): ?\DateTimeInterface {
        return $this->created_at;
    }

    public function setCreatedAt (?\DateTimeInterface $created_at): self {
        $this->created_at = $created_at;

        return $this;
    }

    public function getUpdatedAt (): ?\DateTimeInterface {
        return $this->updated_at;
    }

    public function setUpdatedAt (?\DateTimeInterface $updated_at): self {
        $this->updated_at = $updated_at;

        return $this;
    }

    public function getAdminUserGroupId (): ?int {
        return $this->admin_user_group_id;
    }

    public function setAdminUserGroupId (?int $admin_user_group_id): self {
        $this->admin_user_group_id = $admin_user_group_id;

        return $this;
    }

    public function setUsername (string $username): self {
        $this->username = $username;

        return $this;
    }

    public function getAdminUserGroupName (): ?string {
        return GeneralHelper::getOneInstance()->getAdminUserGroupNameById($this->getAdminUserGroupId());
    }

    /**
     * 新建之前
     * @ORM\PrePersist()
     */
    public function prePersistHook () {
        // 添加默认用户组
        $this->roles = ['ROLE_ADMIN', 'ROLE_SONATA_ADMIN'];
        // 添加创建时间
        $this->created_at = new \DateTime();
    }

    /**
     * 更新之前
     * @ORM\PreUpdate
     * @param PreUpdateEventArgs $eventArgs
     */
    public function preUpdateHook (PreUpdateEventArgs $eventArgs) {
        // 处理密码
        $this->processPreUpdatePassword($eventArgs);
    }

    /**
     * User: Gao
     * Date: 2020/3/20
     * Description: 编辑：用户密码为空时处理
     * @param $eventArgs
     */
    public function processPreUpdatePassword ($eventArgs) {
        if ($eventArgs->hasChangedField('password')) {
            if ($eventArgs->getNewValue('password') === null) {
                $this->password = $eventArgs->getOldValue('password');
            }
        }
    }

    public function isSuperAdmin () {
        return GeneralHelper::getOneInstance()->isSuperAdmin($this->getAdminUserGroupId());
    }

    /**
     * 新建之后 添加日志
     * @ORM\PostPersist()
     */
    public function buildLogByCreate () {
        $description = '用户名:['.$this->getUsername().'] - E-mail:['.$this->getEmail().'] - 用户组:['.$this->getAdminUserGroupName().']';
        LogHelper::buildLog(LogTypeEnum::TYPE_ADMIN_USER_CREATE, $description);
    }

    /**
     * 更新之后 添加日志
     * @ORM\PostUpdate()
     */
    public function buildLogByUpdate () {
        $description = '用户名:['.$this->getUsername().'] - E-mail:['.$this->getEmail().'] - 用户组:['.$this->getAdminUserGroupName().']';
        LogHelper::buildLog(LogTypeEnum::TYPE_ADMIN_USER_UPDATE, $description, $this);
    }

    /**
     * 删除之后 添加日志
     * @ORM\PreRemove()
     */
    public function buildLogByDelete () {
        $description = '用户名:['.$this->getUsername().'] - E-mail:['.$this->getEmail().'] - 用户组:['.$this->getAdminUserGroupName().']';
        LogHelper::buildLog(LogTypeEnum::TYPE_ADMIN_USER_DELETE, $description);
    }

    public function getAvatar (): ?string {
        return $this->avatar;
    }

    public function setAvatar (?string $avatar): self {
        $this->avatar = $avatar;

        return $this;
    }

    /**
     * 获取问候信息
     * @return string
     */
    public function getGreeting () {
        $result = '';

        $h = date('G');
        if ($h >= 6 && $h <= 10)
            $result = '早上好，'.$this->getUsername().'，新的一天请加油哦';
        else if ($h > 10 && $h < 12)
            $result = '上午好，'.$this->getUsername();
        else if ($h >= 12 && $h < 13)
            $result = '中午好，'.$this->getUsername().'，休息一会吧';
        else if ($h >= 13 && $h < 18)
            $result = '下午好，'.$this->getUsername();
        else
            $result = '晚上好，'.$this->getUsername();

        if ($h >= 0 && $h < 6)
            $result .= '，已经很晚了注意休息哈';

        return $result;
    }

    public function getNickname (): ?string {
        return $this->nickname;
    }

    public function setNickname (?string $nickname): self {
        $this->nickname = $nickname;

        return $this;
    }
}
